package cn.chinaiptv.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class LoginFilter
 */
public class LoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public LoginFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// place your code here
		System.out.println("======================");
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String uri = httpServletRequest.getRequestURI();
		System.out.println(uri);
		if (uri.contains("/login.jsp") || uri.contains("LoginServlet")|| uri.contains("/images")|| uri.contains("/css")|| uri.contains("/ImageServlet")|| uri.contains("/LogoutServlet")) {
			chain.doFilter(request, response);
		} else {
			if (httpServletRequest.getSession().getAttribute("user") == null) {
				httpResponse.sendRedirect(httpServletRequest.getContextPath()
						+ "/login.jsp");
			} else {
				chain.doFilter(request, response);
			}

		}
		// pass the request along the filter chain

	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
